<template>
  <div>
    <el-card shadow="never" style="margin-top: 10px">
      <div class="mb-10px">
        <el-text>
          <el-button
            v-hasPerm="['project:tcm:add']"
            type="success"
            @click="handleOpenDialog()"
            style="margin-right: 10px"
          >
            <template #icon><Plus /></template>
            新增
          </el-button>
          <el-text v-if="props.articleTitle !== ''">
            所选论文：《{{ props.articleTitle }} 》 处方
          </el-text>
        </el-text>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column key="name" label="名称" prop="name" min-width="150" align="center" />
        <el-table-column
          key="diseaseCn"
          label="中医病名"
          prop="diseaseCn"
          min-width="200"
          align="center"
        />

        <el-table-column
          key="composition"
          label="组成"
          prop="composition"
          min-width="250"
          align="center"
        />
        <el-table-column
          key="physiologica"
          label="药效"
          prop="physiologica"
          min-width="200"
          align="center"
        />
        <el-table-column
          key="username"
          label="用户名"
          prop="username"
          min-width="80"
          align="center"
        />
        <el-table-column
          key="isSplited"
          label="是否选中"
          prop="isSplited"
          min-width="80"
          align="center"
          v-if="props.topicId != null"
        >
          <template #default="{ row }">
            <el-switch
              inline-prompt
              active-text="使用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0"
              :model-value="getSwitchValue(row.topicTcmId)"
              @change="handleSwitchChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['project:tcm:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['project:tcm:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
            <el-button
              v-hasPerm="['project:compose:query']"
              type="primary"
              size="small"
              link
              @click="handleComposeOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              药味
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 处理详情 -->
    <ComposeDetail ref="composeDetailRef" />

    <TcmEidt
      ref="tcmEidtRef"
      :id="dialog.id"
      :articleId="props.articleId"
      :articleTitle="props.articleTitle"
      :visible="dialog.visible"
      @close="dialog.visible = false"
      @resetQuery="handleQuery"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ArticleTcm",
  inheritAttrs: false,
});

const props = defineProps({
  articleTitle: {
    type: String,
    default: "",
  },
  // 文章Id
  articleId: {
    type: Number,
    default: null,
  },
  topicId: {
    type: Number,
    default: null,
  },
});

import TcmAPI, { TcmPageVO, TcmForm, TcmPageQuery } from "@/api/project/tcm";
import TopicTcmAPI, {
  TopicTcmPageVO,
  TopicTcmForm,
  TopicTcmPageQuery,
} from "@/api/project/topic-tcm";
import TcmEidt from "./TcmEidt.vue";

const dataFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<TopicTcmPageQuery>({
  pageNum: 1,
  pageSize: 10,
  articleId: props.articleId,
  topicId: props.topicId,
});

// 中医处方表格数据
const pageData = ref<TopicTcmPageVO[]>([]);

// 弹窗
const dialog = reactive({
  id: null as number | null, // 明确声明 id 类型为 number | null
  visible: false,
});

const formTopicTcmData = reactive<TopicTcmForm>({});

/** 查询中医处方 */
function handleQuery() {
  dialog.visible = false;
  loading.value = true;

  queryParams.articleId = props.articleId;
  TopicTcmAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
      onQuery();
    })
    .finally(() => {
      loading.value = false;
    });
}

// 使用 watch 监听 props.articleId 的变化
watch(
  () => props.articleId,
  (newVal) => {
    if (newVal !== undefined && newVal !== null) {
      handleQuery();
    }
  },
  { immediate: true }
);

// 暴露方法给父组件
defineExpose({
  handleQuery,
});

const tcmEidtRef = ref();
/** 重置中医处方查询 */
function handleResetQuery() {
  queryParams.pageNum = 1;
  dialog.id = null;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开中医处方弹窗 */
function handleOpenDialog(id?: string) {
  if (props.articleId === 0 || props.articleId === null) {
    ElMessage.warning("请选择文章");
    return;
  }
  if (id === undefined) {
    dialog.id = null; // 确保 id 是 number 类型
  } else {
    dialog.id = Number(id); // 如果 id 为 undefined，则设置为 null
  }
  dialog.visible = true;
}

/** 删除中医处方 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      TcmAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
          onQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}
// 根据 topicTcmId 返回 switch 的值
function getSwitchValue(topicTcmId: number | undefined) {
  return topicTcmId !== undefined && topicTcmId > 0 ? 1 : 0;
}

// 处理 switch 状态变化
function handleSwitchChange(row: TopicTcmPageVO) {
  if (!row || row.id === undefined || row.id <= 0) {
    ElMessage.warning("当前行数据异常，请刷新后重试");
    return;
  }

  loading.value = true;
  const id = row.topicTcmId;
  if (id) {
    const ids = [id].join(",");
    TopicTcmAPI.deleteByIds(ids)
      .then(() => {
        ElMessage.success("修改成功");
        handleQuery();
        onQuery();
      })
      .finally(() => (loading.value = false));
  } else {
    formTopicTcmData.articleId = props.articleId || 0; // 确保默认值为 0
    formTopicTcmData.topicId = props.topicId || 0; // 确保默认值为 0
    formTopicTcmData.tcmId = row.id?.toString() || "";

    TopicTcmAPI.add(formTopicTcmData)
      .then(() => {
        ElMessage.success("修改成功");
        handleQuery();
        onQuery();
      })
      .finally(() => (loading.value = false));
  }
}

const emit = defineEmits(["onQuery"]);
const onQuery = () => {
  emit("onQuery");
};

const composeDetailRef = ref();
// 打开详情弹窗
function handleComposeOpenDialog(id: number) {
  composeDetailRef.value.openDetail(id);
}

onMounted(() => {
  // handleQuery();
});
</script>
